package com.flashcash.kotlin.fragment

import android.app.PendingIntent
import android.content.Intent
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import com.flashcash.kotlin.data.BannerUrlBean
import com.flashcash.kotlin.data.ProductBean
import com.flashcash.kotlin.utils.FirebaseAnalyticsConstants
import com.flashcash.kotlin.utils.FirebaseAnalyticsUtils
import com.flashcash.solu.R
import com.flashcash.solu.app.base.BaseFragment
import com.flashcash.solu.app.base.BaseFragmentView
import com.flashcash.solu.app.base.presenter.BaseFragmentPresenter
import com.flashcash.solu.app.base.presenter.BaseFragmentPresenterImpl
import com.flashcash.solu.bean.LatestLoanAppBean
import com.flashcash.solu.common.EventCollection
import com.flashcash.solu.common.FieldParams
import com.flashcash.solu.common.FieldParamsInt
import com.flashcash.solu.common.TokenManager
import com.flashcash.solu.utils.NotificationUtils
import com.flashcash.solu.utils.StringFormatUtils
import com.flashcash.solu.view.CustomRecyclerView
import com.flashcash.solu.view.MsgBoxActivity
import com.flashcash.solu.widget.XLeoSp
import com.flashcash.solu.widget.xleotoast.XLeoToast
import com.hwangjr.rxbus.RxBus
import com.hwangjr.rxbus.annotation.Subscribe
import com.x.leo.apphelper.data.cache.CacheDataManage
import kotlinx.android.synthetic.main.item_product_enable.view.*
import org.jetbrains.anko.find
import rx.Subscriber
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers

/**
 * Product List Fragment
 */
class ProductFragment : BaseFragment<ProductPresenter>(), ProductFragmentView {
    companion object {
        const val TAG = "ProductFragment"

        private const val EXTRA_PRODUCT_BEAN_LIST = "extra_product_bean_list"

        fun newInstance(productBeanList: ArrayList<ProductBean>): ProductFragment {
            val bundle = Bundle()
            bundle.putSerializable(EXTRA_PRODUCT_BEAN_LIST, productBeanList)

            val instance = ProductFragment()
            instance.arguments = bundle

            return instance
        }
    }

    fun setProductBeanList(productBeanList: ArrayList<ProductBean>) {
        (productRecyclerView.adapter as ProductAdapter).dataChanged(productBeanList)
    }

    private lateinit var productRecyclerView: CustomRecyclerView
    private lateinit var messageImageView: ImageView
    //    private lateinit var bannerView: ImageView
    private lateinit var tvLevel: TextView
    private var firstLoadData: Boolean = true

    override fun initPresenter(): ProductPresenter {
        return ProductPresenterImpl()
    }

    /*override fun doPreBuildHeader(): Boolean {
        return true
    }*/

    override fun getLayoutId(): Int {
        return R.layout.fragment_product
    }

    override fun initView(view: View, savedInstanceState: Bundle?) {
        RxBus.get().register(this)
        productRecyclerView = view.find(R.id.recycler_view_product)
        productRecyclerView.layoutManager = LinearLayoutManager(mActivity, LinearLayoutManager.VERTICAL, false)

        messageImageView = view.find(R.id.iv_message)
//        bannerView = view.find(R.id.banner)
        tvLevel = view.find(R.id.tv_level)

        mPresenter.getBannerUrl()
    }

    override fun setBanner(response: ArrayList<BannerUrlBean>) {
        /*Glide.with(this)
                .load(response[0].url)
                .signature(StringSignature("" + System.currentTimeMillis()))
                .into(bannerView)

        bannerView.setOnClickListener{
            val it = Intent(context, BannerDetailActivity::class.java)
            it.putExtra("detailUrl", response[0].detailUrl)
            startActivity(it)
        }*/
    }

    override fun setDfaultBanner() {
//        bannerView.setBackgroundResource(R.drawable.home_banner);
    }

    override fun onDestroyView() {
        RxBus.get().unregister(this)
        super.onDestroyView()
    }

    @Subscribe
    fun onProductClick(event: EventCollection.DisableProductClickEnent) {
        if (isVisible) {
//            tv_content.setText(R.string.product_disable_tips_content)
//            tv_header.setText(R.string.product_disable_tips_header)
            /*CommonUtils.showMessageDialog(context, false,
                    context?.getString(R.string.product_disable_tips_header),
                    context?.getString(R.string.product_disable_tips_content), { dialog, which ->

            })*/
            XLeoToast.showMessage(R.string.product_disable_tips_content)
        }
    }

    @Subscribe
    fun onShowLevelToast(event: EventCollection.FirstFinishCertifyEvent) {
        //用户首次完成填写四个步骤的资料时，提示
//        XLeoToast.showMessage("Dear user, thank you for your use, show you the following products based on your level")
        //接口还没提供，先提示以下信息
        XLeoToast.showMessage(getString(R.string.tips_credit))
    }

    override fun initData() {
        productRecyclerView.adapter = ProductAdapter(ArrayList(), object : ProductAdapter.OnProductChoseListener {
            override fun productChose(productBean: ProductBean, isOnlyOneChoice: Boolean) {
                if (!TokenManager.getInstance().hasLogin()) {
                    toLogin()
                } else {
                    RxBus.get().post(EventCollection.ProductChoseEvent(productBean))
                }
            }

            override fun hasOtherProductLoaned() {
                XLeoToast.showMessage(R.string.has_other_product_loaned)
            }
        })

        if (arguments != null) {
            val productBeanList = arguments!!.getSerializable(EXTRA_PRODUCT_BEAN_LIST)
            if (productBeanList != null) {
                (productRecyclerView.adapter as ProductAdapter).dataChanged(productBeanList as ArrayList<ProductBean>)
                if (firstLoadData) {
                    firstLoadData = false

                }
                productRecyclerView.scheduleLayoutAnimation()//播放动画
            }
        }

        messageImageView.setOnClickListener {
            messageImageView.isActivated = false
            XLeoSp.getInstance(mActivity).remove(FieldParams.PageStatus
                    .HAS_NEW_MESSAGE)
            val intent = Intent(mActivity, MsgBoxActivity::class.java)
            startActivity(intent)
        }
        //初始化状态
        val aBoolean = XLeoSp.getInstance(mActivity).getBoolean(FieldParams.PageStatus
                .HAS_NEW_MESSAGE)
        messageImageView.isActivated = aBoolean
        messageImageView.isSelected = aBoolean
    }

    override fun infoMessageCallBack() {
        messageImageView.isActivated = true
        messageImageView.isSelected = true
        val intent = Intent(mActivity, MsgBoxActivity::class.java)
        val pendingIntent = PendingIntent.getActivity(mActivity, 0, intent, 0)
        NotificationUtils.showNotificationHasPendingIntent(mActivity, "New Message", "New Loan Information", R.drawable.ic_chat, pendingIntent)
    }

}

interface ProductPresenter : BaseFragmentPresenter {
    fun getBannerUrl()
}

class ProductPresenterImpl : ProductPresenter, BaseFragmentPresenterImpl() {
    override fun getBannerUrl() {
        val subscriber = object : Subscriber<ArrayList<BannerUrlBean>>() {
            override fun onNext(response: ArrayList<BannerUrlBean>) {
                if (isAttached) {
                    (mView as ProductFragmentView).setBanner(response);
                }
            }

            override fun onCompleted() {

            }

            override fun onError(e: Throwable?) {
                if (isAttached) {
                    XLeoToast.showMessage(R.string.show_netwok_wrong);
                    (mView as ProductFragmentView).setDfaultBanner();
                }
            }

        }

        mUserApi.getBannerUrl()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(subscriber)
    }
}

interface ProductFragmentView : BaseFragmentView {
    fun setBanner(response: ArrayList<BannerUrlBean>);
    fun setDfaultBanner();
}

/**
 * Product List adapter
 */
class ProductAdapter(private val productBeanList: ArrayList<ProductBean>?, private val onProductChoseListener: OnProductChoseListener?) : RecyclerView.Adapter<ProductAdapter.ViewHolder>() {
    class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        return when (viewType) {
            ProductStatusEnum.DISABLE.ordinal -> ViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.item_product_disable, parent, false))
            else -> ViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.item_product_enable, parent, false))
        }
    }

    override fun getItemCount(): Int {
        return productBeanList?.size ?: 0
    }

    override fun getItemViewType(position: Int): Int {
        return with(productBeanList!![position]) {
            if (choose) {
                ProductStatusEnum.ENABLE.ordinal
            } else {
                ProductStatusEnum.DISABLE.ordinal
            }
        }
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val latestLoanAppBean = CacheDataManage.obtainData(FieldParamsInt.LATESTBEAN, LatestLoanAppBean::class.java)

        with(productBeanList!![position]) {
            val hasProductLoaned = TokenManager.getInstance().hasLogin() && latestLoanAppBean != null && FieldParams.LoanStatus.SUBMITTED == latestLoanAppBean.status
            val isThisProductLoaned = hasProductLoaned && id == latestLoanAppBean?.productId ?: false

//            holder.itemView.text_view_product_name.text = name

            /*if (isThisProductLoaned) {
                holder.itemView.text_view_product_tips.visibility = View.VISIBLE
            } else {
                holder.itemView.text_view_product_tips.visibility = View.GONE
            }*/

            holder.itemView.text_view_product_min_amount_max_amount.text = (StringFormatUtils.moneyFormatWithSplitWithUnitWithoutDecimal(minAmount, holder.itemView.context) + "-" + StringFormatUtils.moneyFormatWithSplitWithUnitWithoutDecimal(maxAmount, holder.itemView.context))

            if (maxPeriod == minPeriod) {
                holder.itemView.text_view_product_min_period_max_period.text = "${minPeriod} Days"
            } else {
                holder.itemView.text_view_product_min_period_max_period.text = "${minPeriod}-${maxPeriod} Days"
            }

//            holder.itemView.text_view_product_description.text = description

            when (getItemViewType(position)) {
                ProductStatusEnum.DISABLE.ordinal -> {
                    holder.itemView.button_product_choose.setOnClickListener {
                        RxBus.get().post(EventCollection.DisableProductClickEnent())
                    }
                    FirebaseAnalyticsUtils.logEvent(FirebaseAnalyticsConstants.Event.BTN_CLICK_DISABLED_PRODUCT, null)
                    holder.itemView.setOnClickListener {
                        RxBus.get().post(EventCollection.DisableProductClickEnent())
                    }
                }
                else -> {
                    val isOnlyOneChoice = maxAmount == minAmount && maxPeriod == minPeriod
                    FirebaseAnalyticsUtils.logEvent(FirebaseAnalyticsConstants.Event.BTN_CLICK_ENABLED_PRODUCT, null)
                    holder.itemView.button_product_choose.setOnClickListener {
                        if (!hasProductLoaned || isThisProductLoaned) {

                            onProductChoseListener?.productChose(this, isOnlyOneChoice)
                        } else {
                            onProductChoseListener?.hasOtherProductLoaned()
                        }
                    }
                    holder.itemView.setOnClickListener {
                        if (!hasProductLoaned || isThisProductLoaned) {

                            onProductChoseListener?.productChose(this, isOnlyOneChoice)
                        } else {
                            onProductChoseListener?.hasOtherProductLoaned()
                        }
                    }
                }
            }
        }
    }

    fun dataChanged(productBeanList: ArrayList<ProductBean>?) {
        this.productBeanList?.clear()
        this.productBeanList?.addAll(productBeanList!!)
        this.notifyDataSetChanged()
    }

    interface OnProductChoseListener {
        fun productChose(productBean: ProductBean, isOnlyOneChoice: Boolean)
        fun hasOtherProductLoaned()
    }
}

enum class ProductStatusEnum {
    ENABLE, DISABLE
}
